<?php

class UsersController extends BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /users
	 *
	 * @return Response
	 */
	public function __construct()
    {
        $this->beforeFilter('isAdminGet', array('on' => 'get', 'except'=>array('login', 'doLogout', 'showChangePassword', 'recoverAdmin', 'fun')));
        $this->beforeFilter('isAdminPost', array('on' => 'post', 'except'=>array('doLogin', 'changePassword')));
    }

	public function index()
	{
		//
	}
	public function doLogout()
	{
		Auth::logout();
		return Redirect::intended('login');
	}
	public function login()
	{
		return View::make('users.login');
	}

	public function showChangePassword()
	{
		return View::make('users.passwordRecovery');
	}

	public function changePassword()
	{
		$error = false;
		$message = "";
		$response;
		try
		{
			$pw1 = Input::get("pw1");
			$pw2 = Input::get("pw2");
			if($pw1 != $pw2)
			{
				throw new  Exception("Las contraseñas no coinciden.");
				
			}
			$user = Auth::user();
			$user->password = $pw1;
			$user->password_changed = false;
			$user->save();

			//Mail::pretend();
			$data = array("username"=>$user->id, "password" => $pw1);
			Mail::send('emails.passwordChanged', $data, function($message) use ($user)
			{
			    $message->from('admin@labbyinventory.x10host.com', 'Carlos Celis');

			    $message->to($user->email);
			});

		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}
	public function regeneratePassword()
	{
		$error = false;
		$message = "";
		$response;
		$user;
		try
		{
			$user = User::find(Input::get("pk"));
			if($user == null)
			{
				throw new  Exception("Error interno. Intenta de nuevo.");
				
			}
			$generatedPassword = Util::generateRandomString(7);
			//$generatedPassword = "qqq";
			$user->password = $generatedPassword;
			$user->password_changed = true;
			$user->save();

			//Mail::pretend();
			$data = array("password" => $generatedPassword);
			Mail::send('emails.passwordChanged', $data, function($message) use ($user)
			{
			    $message->from('admin@labbyinventory.x10host.com', 'Carlos Celis');
			    
			    $message->to($user->email);
			});
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}
	public function doLogin()
	{
		if(Auth::attempt(array('id' => Input::get('id'), 'password' => Input::get('password'))))
		{
			if(Auth::user()->password_changed)
			{
				return Redirect::intended('passwordRecovery');
			}else
			{
				return Redirect::intended('/');
			}
		}
		else
		{
			$message = "Su información de ingreso es errada. Por favor intente nuevamente";
			return View::make('users.login')->with('loginError', $message);
		}
	}

	public function showUsers()
	{
		$users = User::where('user_type_fk', '!=', Config::get("globals.adminTypePk"));
		$firstLastname = Input::get('firstLastname');
		$name = Input::get('name');
		$secondLastname = Input::get('secondLastname');
		$email = Input::get('email');
		$phone = Input::get('phone');

		if($firstLastname != "")
		{
			$users->where('first_lastname', 'LIKE', "%$firstLastname%");
		}
		if($name != "")
		{
			$users->where("name", "LIKE", "%$name%");
		}
		if($secondLastname != "")
		{
			$users->where("second_lastname", "LIKE", "%$secondLastname%");
		}

		if($email != "")
		{
			$users->where("email", "LIKE", "%$email%");
		}
		if($phone != "")
		{
			$users->where("phone", "LIKE", "%$phone%");
		}
		$users = $users->paginate(10);
		$trashedUsers = User::onlyTrashed()->paginate(10);
		return View::make('users.usersHome')->with('users', $users)->with('trash', $trashedUsers);
	}

	public function getUserInfo()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$user = User::withTrashed()->find(Input::get('pk'));
			if($user == null)
			{
				$error = true;
				$message = "Error: no se encontró el usuario.";
			}
			else
			{
				$html = View::make('users.moreInfoPopup')->with('user', $user)->render();
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "html" => $html);
		}
		return json_encode($response);
	}

	public function getUserEdit()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$user = User::find(Input::get('pk'));
			if($user == null)
			{
				$error = true;
				$message = "Error: no se encontró el usuario.";
			}
			else
			{
				$html = View::make('users.editPopup')->with('user', $user)->render();
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "html" => $html, "user"=>$user->toJson());
		}
		return json_encode($response);
	}

	public function getUserCreate()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$html = View::make('users.createPopup')->render();
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$user = new User;
			$user->user_type_fk = 2;
			$response = array("error" => $error, "html" => $html, "user"=>$user->toJson());
		}
		return json_encode($response);
	}

	public function saveUser()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		$generatedPassword;
		$userArray = Input::get('user');
		
		try
		{
			$user = null;
			
			if(isset($userArray['pk']))
			{
				$user = User::find($userArray['pk']);
			}

			$isUpdate = isset($userArray['pk']) && $user != null;
			if(!$isUpdate)
			{
				$user = new User;
				$user->user_type_fk = 2;
				$generatedPassword = Util::generateRandomString(7);
				$user->password = $generatedPassword;
				$user->password_changed = true;
			}
			
			if($user->email != $userArray['email'] && !User::withTrashed()->where("email", "=", $userArray['email'])->get()->isEmpty())
			{
				throw new Exception("Ya existe un usuario con el email ".$userArray['email']);
				
			}

			if($user->id != $userArray['id'] && !User::withTrashed()->where("id", "=", $userArray['id'])->get()->isEmpty())
			{
				throw new Exception("Ya existe un usuario con el usuario ".$userArray['id']);
				
			}
			
			//Validations
			$validator = Validator::make(
			    array(
			    	'id'=> $userArray['id'],
			        'name' => $userArray['name'],
			        'first_lastname' => $userArray['first_lastname'],
			        'second_lastname' => $userArray['second_lastname'],
			        'date_of_birth' => $userArray['date_of_birth'],
			        'address' => $userArray['address'],
			        'phone'=> $userArray['phone']
			    ),
			    array(
			    	'id'=> 'required|min:7|max:249',
			        'name' => 'required|min:2|max:249',
			        'first_lastname' => 'required|max:249|min:2',
			        'second_lastname' => 'required|max:249|min:2',
			        'date_of_birth'=> 'required|olderThan',
			        'address'=>'max:249',
			        'phone'=>'required|numeric|digits_between:7,10'
			    )
			);
			
			if($validator->fails())
			{
				$ms = "";
				foreach ($validator->messages()->all('-:message') as $message)
				{
				    $ms .= $message;
				}
				throw new Exception($ms);
				
			}
			//$generatedPassword = "aaa";
			//$user->password = $generatedPassword;
			$user->name = $userArray['name'];
			$user->first_lastname = $userArray['first_lastname'];
			$user->second_lastname = $userArray['second_lastname'];
			$user->id = $userArray['id'];
			$user->date_of_birth = $userArray['date_of_birth'];
			$user->address = $userArray['address'];
			$user->email = $userArray['email'];
			$user->phone = $userArray['phone'];
			
			$user->active_user = true;
			$user->save();

			//Mail::pretend();
			if(!$isUpdate)
			{
				$data = array("username"=>$user->id, "password" => $generatedPassword);
				Mail::send('emails.welcome', $data, function($message) use ($user)
				{
				    $message->from('admin@labbyinventory.x10host.com', 'Carlos Celis');

				    $message->to($user->email);
				});
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}

	public function deleteUser()
	{
		$error = false;
		$message = "";
		$response;
		try
		{
			$user = User::find(Input::get('user'));
			if($user != null)
			{
				$requests = $user->createdRequests;
				if($requests == null || $requests->isEmpty())
				{
					$user->forceDelete();
				}
				else
				{	if(Util::userHasPendingRequests($requests))
					{
						throw new Exception("El usuario tiene solicitudes pendientes. Resuelva las solicitudes antes de proceder.");
						
					}
					$user->delete();
				}
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}

	public function restoreUser()
	{
		$error = false;
		$message = "";
		$response;
		try
		{
			$user = User::onlyTrashed()->find(Input::get('id'));
			if($user != null)
			{
				$user->restore();
			}
			else
			{
				throw new Exception("El usuario no fue encontrado. Por favor refresque la página e intente nuevamente.");
				
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}
	public function fun()
	{
		return Hash::make(Input::get('john'));
	}
	/*public function recoverAdmin()
	{
		$user = User::find("1");
		$user->password = "aaa";
		$user->save();
	}

	public function test()
	{
		Input::merge(array('pk' => '11'));
		$this->regeneratePassword();
		echo "sent";
	}*/
}